/*
@Copyright:Copyright(c)2012
@Company:Morningstar
@Title:Fairvalue Chart Setting panel
@description:switch coverage uninverse of fairvalue chart
@author:Wind
@Date:2012.05.09
@version:1.0
@History:
*/

/*
@Dependence
//js
require(lib/jquery.js)
require(lib/jquery.json.min.js)
require(js/ui/util.js)

//css
require(qs.css)
require(fairvalue_settingpanel.css)
require(style.css)
*/

/*
@Name:FairValueSettingPanel
@Description:create the setting panel of fairvalue
@Param:
    container - the container that contain the fairvalue setting panel
    cfg       - the optional configuration
@Return: undefined
*/
if(!QS){
    QS={};
}
QS.FairValue_MenuData=[
        {txt:'All Rated Stocks', val:'AllStocks'},
        {txt:'Super Sector',subMenu:[{txt:'Cyclical'},{txt:'Defensive'},{txt:'Sensitive'}]},
        {txt:'Sector',subMenu:[{txt:'Basic Materials'},{txt:'Consumer Cyclical'},{txt:'Financial Services'},{txt:'Real Estate'},{txt:'Consumer Defensive'},{txt:'Healthcare'},{txt:'Utilities'},{txt:'Communication Services'},{txt:'Energy'},{txt:'Industrials'},{txt:'Technology'}]},
        {txt:'Industry', subMenu:[
            {txt:'Basic Materials',subMenu:[{txt:'Agricultural Inputs'},{txt:'Aluminum'},{txt:'Building Materials'},{txt:'Chemicals'},{txt:'Coal'},{txt:'Copper'},{txt:'Gold'},{txt:'Industrial Metals & Minerals'},{txt:'Lumber & Wood Production'},{txt:'Paper & Paper Products'},{txt:'Silver'},{txt:'Specialty Chemicals'},{txt:'Steel'}]},                
            {txt:'Consumer Cyclical',subMenu:[{txt:'Advertising Agencies'},{txt:'Apparel Manufacturing'},{txt:'Apparel Stores'},{txt:'Auto & Truck Dealerships'},{txt:'Auto Manufacturers'},{txt:'Auto Parts'},{txt:'Broadcasting - Radio'},{txt:'Broadcasting - TV'},{txt:'Department Stores'},{txt:'Footwear & Accessories'},{txt:'Gambling'},{txt:'Home Furnishings & Fixtures'},{txt:'Home Improvement Stores'},{txt:'Leisure'},{txt:'Lodging'},{txt:'Luxury Goods'},{txt:'Marketing Services'},{txt:'Media - Diversified'},{txt:'Packaging & Containers'},{txt:'Personal Services'},{txt:'Publishing'},{txt:'Recreational Vehicles'},{txt:'Residential Construction'},{txt:'Resorts & Casinos'},{txt:'Restaurants'},{txt:'Rubber & Plastics'},{txt:'Specialty Retail'},{txt:'Textile Manufacturing'}]},
            {txt:'Financial Services',subMenu:[{txt:'Asset Management'},{txt:'Banks - Global'},{txt:'Banks - Regional - Africa'},{txt:'Banks - Regional - Asia'},{txt:'Banks - Regional - Australia'},{txt:'Banks - Regional - Canada'},{txt:'Banks - Regional - Europe'},{txt:'Banks - Regional - Latin America'},{txt:'Banks - Regional - US'},{txt:'Capital Markets'},{txt:'Credit Services'},{txt:'Financial Exchanges'},{txt:'Insurance - Diversified'},{txt:'Insurance - Life'},{txt:'Insurance - Property & Casualty'},{txt:'Insurance - Reinsurance'},{txt:'Insurance - Specialty'},{txt:'Insurance Brokers'},{txt:'Savings & Cooperative Banks'},{txt:'Specialty Finance'}]},
            {txt:'Real Estate',subMenu:[{txt:'Real Estate - General'},{txt:'Real Estate Services'},{txt:'REIT - Diversified'},{txt:'REIT - Healthcare Facilities'},{txt:'REIT - Hotel & Motel'},{txt:'REIT - Industrial'},{txt:'REIT - Office'},{txt:'REIT - Residential'},{txt:'REIT - Retail'}]},
            {txt:'Consumer Defensive',subMenu:[{txt:'Beverages - Brewers'},{txt:'Beverages - Soft Drinks'},{txt:'Beverages - Wineries & Distilleries'},{txt:'Confectioners'},{txt:'Discount Stores'},{txt:'Education & Training Services'},{txt:'Farm Products'},{txt:'Food Distribution'},{txt:'Grocery Stores'},{txt:'Household & Personal Products'},{txt:'Packaged Foods'},{txt:'Pharmaceutical Retailers'},{txt:'Tobacco'}]},
            {txt:'Healthcare',subMenu:[{txt:'Biotechnology'},{txt:'Diagnostics & Research'},{txt:'Drug Manufacturers - Major'},{txt:'Drug Manufacturers - Specialty & Generic'},{txt:'Health Care Plans'},{txt:'Long-Term Care Facilities'},{txt:'Medical Care'},{txt:'Medical Devices'},{txt:'Medical Distribution'},{txt:'Medical Instruments & Supplies'}]},
            {txt:'Utilities',subMenu:[{txt:'Utilities - Diversified'},{txt:'Utilities - Independent Power Producers'},{txt:'Utilities - Regulated Electric'},{txt:'Utilities - Regulated Gas'},{txt:'Utilities - Regulated Water'}]},
            {txt:'Communication Services',subMenu:[{txt:'Pay TV'},{txt:'Telecom Services'}]},                
            {txt:'Energy',subMenu:[{txt:'Oil & Gas Drilling'},{txt:'Oil & Gas E&P'},{txt:'Oil & Gas Equipment & Services'},{txt:'Oil & Gas Integrated'},{txt:'Oil & Gas Midstream'},{txt:'Oil & Gas Refining & Marketing'}]},
            {txt:'Industrials',subMenu:[{txt:'Aerospace & Defense'},{txt:'Airlines'},{txt:'Airports & Air Services'},{txt:'Business Equipment'},{txt:'Business Services'},{txt:'Conglomerates'},{txt:'Diversified Industrials'},{txt:'Engineering & Construction'},{txt:'Farm & Construction Equipment'},{txt:'Industrial Distribution'},{txt:'Infrastructure Operations'},{txt:'Integrated Shipping & Logistics'},{txt:'Metal Fabrication'},{txt:'Pollution & Treatment Controls'},{txt:'Railroads'},{txt:'Rental & Leasing Services'},{txt:'Security & Protection Services'},{txt:'Shipping & Ports'},{txt:'Staffing & Outsourcing Services'},{txt:'Tools & Accessories'},{txt:'Truck Manufacturing'},{txt:'Trucking'},{txt:'Waste Management'}]},
            {txt:'Technology',subMenu:[{txt:'Communication Equipment'},{txt:'Computer Distribution'},{txt:'Computer Systems'},{txt:'Consumer Electronics'},{txt:'Contract Manufacturers'},{txt:'Data Storage'},{txt:'Electronic Components'},{txt:'Electronic Gaming & Multimedia'},{txt:'Electronics Distribution'},{txt:'Health Information Services'},{txt:'Information Technology Services'},{txt:'Internet Content & Information'},{txt:'Scientific & Technical Instruments'},{txt:'Semiconductor Equipment & Materials'},{txt:'Semiconductor Memory'},{txt:'Semiconductors'},{txt:'Software - Application'},{txt:'Software - Infrastructure'},{txt:'Solar'}]}]
        },
        {txt:'Size of Moat (Business Quality)',subMenu:[{txt:'Wide'},{txt:'Narrow'},{txt:'None'}]},
        {txt:'Fair Value Uncertainty (Business Risk)',subMenu:[{txt:'Low'},{txt:'Medium', val:'Med'},{txt:'High'}]},
        {txt:'Index',subMenu:[{txt:'NYSE'},{txt:'Nasdaq', val:'NAS'}]}
];
QS.DataParsed=false;
var FairValueSettingPanel=function(container,cfg,callback){
    //this.fairvalueObj=fairvalueObj;
	var t=QS_Lang.fairvalue;
    this.container=container;
    this.callback=callback||{};    
    this.el=null;
    this.config={currentTicker:{val:'AllStocks', txt:'All Rated Stocks'}};
    this.html='<div class="rtq-fairvalues-view"><h3>Coverage Universe</h3><div class="bd"><div class="qs-fairvalue-sp-sct rtq-ddl"><div class="rtq-ddl-ipt" readonly="readonly" val=""></div></div></div><div class="rtq-fairvaluesetting-ft"></div></div>';
    $.extend(this.config,cfg,true);
    this.init();
};
FairValueSettingPanel.prototype={
    init:function(){
        this.el=$(this.html);
        if(this.container){
           this.el.appendTo(this.container)
        };
        this.sectorMenu = null;
        this.sectorHandler = this.el.find('.qs-fairvalue-sp-sct');
        this.sectorInfo = this.sectorHandler.find('.rtq-ddl-ipt');
        this.menuObj = null;              
        this.sectorInfo.text(this.config.currentTicker.txt);    
        this._eventHandler();
    },
    _createSectorMenu: function(o){
        var self = this;
        if(QS.DataParsed==false){
            this._parseData(QS.FairValue_MenuData);
        }
        QS.DataParsed=true;      
        this.sectorMenu = new Util.CascadeMenu(self.sectorHandler.eq(0), {
            autoHide: true,            
            display: false,
            fixedDirection: false,
            showTitle: true
        }, QS.FairValue_MenuData, {
            onClick: function(item){
                self.sectorInfo.text(item.data.txt);
                self.menuObj.removeClass('on'); 
                self._activeItem(item);
                if(item.el.find('ul.rtq-menu-ul').length>0){return false;}
                self.callback && self.callback.onClick && self.callback.onClick(item);
            }
        });        
        self.menuObj=this.sectorHandler.find('.rtq-menu-item');
        if(self.sectorMenu.getItemByVal(self.config.currentTicker.val)){
            self._activeItem(self.sectorMenu.getItemByVal(self.config.currentTicker.val));
        }
    },
    _parseData:function(menuData){
        //console.log('e');
        var k = menuData.length;
        for(var i=0;i<k;i++){
            if(typeof menuData[i].val=='undefined'){
                menuData[i].val=menuData[i].txt.replace('&', '!');;
            }
            if(menuData[i].subMenu){                
                this._parseData(menuData[i].subMenu);
            }
        }
    },
    _activeItem: function(item){
        //console.log('f');
        if(item.parent){
            this._activeItem(item.parent);
        }
        item.el.addClass('on');
    },
    _eventHandler: function(){
        var self = this;
        var timeoutObj;
        var delay = 200;
        this.sectorHandler.unbind('mouseover').bind('mouseover', function(e){
            if ($(e.target).hasClass("qs-fairvalue-sp-sct")) {
                if(self.sectorMenu==null){
                    self._createSectorMenu();
                }
                clearTimeout(timeoutObj);
                timeoutObj = setTimeout(function(){
                    self.sectorMenu.show();
                }, delay);
            }
        }).unbind('mouseout').bind('mouseout', function(e){
            if (!Util.contains(self.sectorHandler[0],e.relatedTarget)) {
                if(self.sectorMenu!=null){
                    clearTimeout(timeoutObj);
                    timeoutObj = setTimeout(function(){
                        self.sectorMenu.hide();                    
                    }, delay);
                }
            }            
        });       
    },
    clear:function(){
        for(var p in this){
            if(!p || p == 'clear'){continue;}
            this[p] = null;
            delete this[p];
       }
    }
};